<?php


class helper{

	static function db_mssql_check_xss () {
		$url = html_entity_decode(urldecode($_SERVER['QUERY_STRING']));
		if ($url) {
			if ((strpos($url, '<') !== false) ||
				(strpos($url, '>') !== false) ||
				(strpos($url, '"') !== false) ||
				(strpos($url, '\'') !== false) ||
				(strpos($url, './') !== false) ||
				(strpos($url, '../') !== false) ||
				(strpos($url, '--') !== false) ||
				(strpos($url, '.php') !== false)
			   )
			{
				die("Попытка взлома!");
			}
		}
		$url = html_entity_decode(urldecode($_SERVER['REQUEST_URI']));
		if ($url) {
			if ((strpos($url, '<') !== false) ||
				(strpos($url, '>') !== false) ||
				(strpos($url, '"') !== false) ||
				(strpos($url, '\'') !== false)
			   )
			{
				die("Попытка взлома!");
			}
		}
	
	}
	
	
	static function office_secure($check_string)
	{
	    $ret_string = $check_string;
	    $ret_string = htmlspecialchars ($ret_string);
	    $ret_string = strip_tags ($ret_string);
	    $ret_string = trim ($ret_string);
	    $ret_string = str_replace ('\\l', '', $ret_string);
	    $ret_string = str_replace (' ', '', $ret_string);
	    $ret_string  = str_replace("'", "", $ret_string );
	    $ret_string  = str_replace("\"", "",$ret_string );
	    $ret_string  = str_replace("--", "",$ret_string );
	    $ret_string  = str_replace("#", "",$ret_string );
	    $ret_string  = str_replace("$", "",$ret_string );
	    $ret_string  = str_replace("%", "",$ret_string );
	    $ret_string  = str_replace("^", "",$ret_string );
	    $ret_string  = str_replace("&", "",$ret_string );
	    $ret_string  = str_replace("(", "",$ret_string );
	    $ret_string  = str_replace(")", "",$ret_string );
	    $ret_string  = str_replace("=", "",$ret_string );
	    $ret_string  = str_replace("+", "",$ret_string );
	    $ret_string  = str_replace("%00", "",$ret_string );
	    $ret_string  = str_replace(";", "",$ret_string );
	    $ret_string  = str_replace(":", "",$ret_string );
	    $ret_string  = str_replace("|", "",$ret_string );
	    $ret_string  = str_replace("<", "",$ret_string );
	    $ret_string  = str_replace(">", "",$ret_string );
	    $ret_string  = str_replace("~", "",$ret_string );
	    $ret_string  = str_replace("`", "",$ret_string );
	    $ret_string  = str_replace("%20and%20", "",$ret_string );
	    $ret_string = stripslashes ($ret_string);
	    return $ret_string;
	}
	
	static function check_sql_inject() 
	  { 
	    $badchars = array(	"--","truncate","tbl_","exec",	";","'","*","/"," \ ","drop",
	    	"select","update","delete","where", "-1", "-2", "-3","-4", "-5", "-6", "-7", "-8", "-9",); 
	    foreach($_POST as $value) 
	    { 
		    foreach($badchars as $bad) 
		    {
			    if(strstr(strtolower($value),$bad)<>FALSE) 
			    {
			    	die('SQL Injection Inside');
			    }
			}
	    } 
	  } 
	
		/*
		@param string name
		@param any type
		@param int expired in minutes
	*/
	
	function setCache($sName,$oCacheObject,$iExpired=60){
		
		$sCachePath='cache/';
		
		$time=time()+($iExpired*60);
		
		$object=serialize(array('expired'=>$time,'content'=>$oCacheObject));
		
		file_put_contents($sCachePath.md5($sName), $object);
	
	}
	
	function getCache($sName){
		
		$sCachePath='cache/'.md5($sName);
		
		if(file_exists($sCachePath)){
		
			$object=file_get_contents($sCachePath);
			$sObj=unserialize($object);
			
			if($sObj['expired'] > time()){
			
				return $sObj['content'];
		
			} else {
			
				unlink($sCachePath);
				return false;
			}
			
		} else {
		
			return false;
		}
		
	}//getCache
	
//Общая статистика, на всех страницах
	function stat() {
		if(!$tot=helper::getCache('stat')){
			$db=WORLD;
			list($total1)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) as count1 FROM RF_USER.dbo.tbl_UserAccount"));
			list($total2)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) as count2 FROM $db.dbo.tbl_base"));
			list($total3)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) as count3 FROM $db.dbo.tbl_base WHERE DCK=1"));
			list($total4)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) as count4 FROM $db.dbo.tbl_base WHERE DCK=0 AND Race=2"));
			list($total5)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) as count5 FROM $db.dbo.tbl_base WHERE DCK=0 AND Race=1"));
			list($total6)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) as count5 FROM $db.dbo.tbl_base WHERE DCK=0 AND Race=0"));
			list($total7)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) as cnt FROM $db.dbo.tbl_Guild WHERE DCK=0"));
			$tot = array($total1,$total2,$total3,$total4,$total5,$total6,$total7);
			$this->tpl->assign('tot1',$tot);
			helper::setCache('stat',$tot);
		}
	$this->tpl->assign('tot1',$tot);
	}
	
	function analyze($var='') {
		$var = (preg_match("#[^a-zA-Z0-9а-яА-Я_]#", $var)) ? "" : $var;
		return $var;
	}	
	
	function checkemail($mail) {
		$stop='';
		$mail = strtolower($mail);
		if ((!$mail) || ($mail=="") || (!preg_match("/^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,6}$/", $mail))) $stop = "Ошибка, неправильно указан E-Mail!<br>Пожалуйста, используйте стандартный формат (<b>email@domain.com</b>)";
		if ((strlen($mail) >= 4) && (substr($mail, 0, 4) == "www.")) $stop = "Ошибка, неправильно указан E-Mail!<br>Пожалуйста, не указывайте в начале адреса (<b>www.</b>)";
		if (strrpos($mail, " ") > 0) $stop = "Ошибка, неправильно указан E-Mail!<br>Пожалуйста, не используйте пробелов.";
		return $stop;
	}
	
//онлайн по часам
	function usernum () {
		if(!$result=helper::getCache('usernum')){
			$api=new Chartapi;
			$world=WORLD;
			$res=db_mssql_query("SELECT TOP 24 serial,CONVERT(VARCHAR, dtDate, 108) AS hour, 
			nMaxUser FROM $world.dbo.tbl_log_usernum 
			ORDER BY dtDate DESC") or die(mssql_get_last_message());
			$datax=array();
			$datay=array();
			while ($data=db_mssql_fetchrow($res))
			{
					$datax[$data['serial']] = substr($data['hour'], 0, 2);
					$datay[$data['serial']] = $data['nMaxUser'];
			}
			ksort($datax);
			ksort($datay);
			$api->cht="lc";
			$api->chco="0000FF";
			$api->chs="500x500";
			$api->chls=$datay;
			$api->chtt='%D0%9E%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD%20%D0%B8%D0%B3%D1%80%D0%BE%D0%BA%D0%BE%D0%B2%20%D0%BF%D0%BE%20%D1%87%D0%B0%D1%81%D0%B0%D0%BC';
			$api->chxt="x,y";
			$api->chxl='0:|'.implode('|',$datax);
			$api->chd=$datay;
			$api->chg="4.34,4.34";
			$api->chf='c,ls,0,CCCCCC,0.13,FFFFFF,0.087';
			$result = $api->generate(true);
			
			helper::setCache('usernum',$result);
		}
		return $result;
	}
//текущий онлайн
	function race_online() {
		if(!$result=helper::getCache('race_online')){
			$db=WORLD;
			list($count_acc)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) AS count FROM $db.dbo.tbl_general,$db.dbo.tbl_base
			WHERE $db.dbo.tbl_general.OnlineStatus>=dateadd(minute,-5,getdate())
			AND $db.dbo.tbl_base.Serial=$db.dbo.tbl_general.Serial AND $db.dbo.tbl_base.race=4"));
		
			list($count_bcc1)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) AS count FROM $db.dbo.tbl_general,$db.dbo.tbl_base
			WHERE $db.dbo.tbl_general.OnlineStatus>=dateadd(minute,-5,getdate()) AND $db.dbo.tbl_base.Serial=$db.dbo.tbl_general.Serial
			AND $db.dbo.tbl_base.race=0"));
		
			list($count_bcc2)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) AS count FROM $db.dbo.tbl_general,$db.dbo.tbl_base
			WHERE $db.dbo.tbl_general.OnlineStatus>=dateadd(minute,-5,getdate()) AND $db.dbo.tbl_base.Serial=$db.dbo.tbl_general.Serial
			AND $db.dbo.tbl_base.race=1"));
		
			list($count_ccc1)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) AS count FROM $db.dbo.tbl_general,$db.dbo.tbl_base
			WHERE $db.dbo.tbl_general.OnlineStatus>=dateadd(minute,-5,getdate()) AND $db.dbo.tbl_base.Serial=$db.dbo.tbl_general.Serial
			AND $db.dbo.tbl_base.race=2"));
		
			list($count_ccc2)=db_mssql_fetchrow(db_mssql_query("SELECT COUNT(*) AS count FROM $db.dbo.tbl_general,$db.dbo.tbl_base
			WHERE $db.dbo.tbl_general.OnlineStatus>=dateadd(minute,-5,getdate()) AND $db.dbo.tbl_base.Serial=$db.dbo.tbl_general.Serial
			AND $db.dbo.tbl_base.race=3"));
		
			$count_bcc=$count_bcc1+$count_bcc2;
			$count_ccc=$count_ccc1+$count_ccc2;
			$api=new Chartapi;
			$api->cht="p";
			$api->chco=APICOLOR;
			$api->chs="400x200";
			$api->chtt="%D0%A2%D0%B5%D0%BA%D1%83%D1%89%D0%B8%D0%B9%20%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD";
			$api->chd=array($count_acc,$count_bcc,$count_ccc);
			$api->chl=array(
						"%D0%90%D0%BA%D1%80%D0%B5%D1%82%D0%B8%D1%8F+($count_acc)",
						"%D0%91%D0%B5%D0%BB%D0%BB%D0%B0%D1%82%D0%BE+($count_bcc)",
						"%D0%9A%D0%BE%D1%80%D0%B0+($count_ccc)");
			$result = $api->generate();
			helper::setCache('race_online',$result);
		}
		return $result;
	}
/**
 * Обрезка лишнего
 *
 * @param string $char 
 * @return void
 * @author NetSoul
 */
	function preg_name($char) {
		$char=$char;
		$char=str_replace('%26%2365533%3B','',$char);
		$char=str_replace('%00','',$char);
		$char=str_replace('%2A31206','',$char);
		$return=urldecode($char);
		return trim($return, "\x00..\x1F");
	}
/**
 * Подсветка русских букв
 *
 * @param string $text 
 * @param string $html1 
 * @param string $html2 
 * @return string
 * @author NetSoul
 */
	function ru_text($text,$html1="<b>",$html2="</b>") {
		$string=helper::preg_name(trim($text));
		$rulang='йцукенгшщзхфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ';
		$ru_array=str_split($rulang);
		for ($i=0; $i < count($ru_array); $i++) { 
			$string  = str_replace($ru_array[$i], $html1.$ru_array[$i].$html2, $string );
		}
		return $string ;
	}
//иконки расы\пола
	function get_race($r,$sex=true) {
		if($sex){
		if($r==0) return helper::icon('template/img/icon_bcc.gif').helper::icon('template/img/male.gif');
		if($r==1) return helper::icon('template/img/icon_bcc.gif').helper::icon('template/img/female.gif');
		if($r==2) return helper::icon('template/img/icon_ccc.gif').helper::icon('template/img/male.gif');
		if($r==3) return helper::icon('template/img/icon_ccc.gif').helper::icon('template/img/female.gif');
		if($r==4) return helper::icon('template/img/icon_acc.gif');
		} else {
		if($r==0) return helper::icon('template/img/icon_bcc.gif');
		if($r==1) return helper::icon('template/img/icon_ccc.gif');
		if($r==2) return helper::icon('template/img/icon_acc.gif');	
		}
	}
	
	function icon($filename,$tip='',$style='') {
		return "<img src='{$filename}' border=0 title='{$tip}' $style/>";
	}
//топ 100
	function top100() {
	if(!$result=helper::getCache('top100')){
			$world=WORLD;
			$query=db_mssql_query("
		SELECT TOP 100
			$world.dbo.tbl_base.Name,
			$world.dbo.tbl_base.Lv,
			$world.dbo.tbl_base.Race,
			$world.dbo.tbl_general.PvpPoint,
			$world.dbo.tbl_general.GuildSerial
		FROM 
			$world.dbo.tbl_base,
			$world.dbo.tbl_general
		WHERE 
			$world.dbo.tbl_base.Serial=$world.dbo.tbl_general.Serial 
		AND
			$world.dbo.tbl_base.AccountSerial<2000000000 
		AND
			LEFT($world.dbo.tbl_base.Name,1)<>'*'
		ORDER BY 
			$world.dbo.tbl_general.PvpPoint 
			DESC");
			$table=new CI_Table;
			$tmpl = array (
			'table_open'=>'<table cellspacing="0"><thead>',
			'heading_cell_start'=>'<th>',
			'heading_cell_end'=>'</th>',
			'row_start'=>'</thead><tr class="tc">',
			'row_alt_start'=>'<tr class="tc">',
			);
			
			$table->set_template($tmpl);
			$table->set_heading('№', 'Имя','Уровень','Раса','ПвП Очков','Гильдия');
			$i=1;
			while (list($Name,$Lv,$Race,$PvpPoint,$GuildSerial) = db_mssql_fetchrow($query))
			{
				list($id)=db_mssql_fetchrow(db_mssql_query("SELECT id FROM $world.dbo.tbl_Guild WHERE Serial=".$GuildSerial));
				if($id=='') $id='Не в гильдии';
				$table->add_row ($i,helper::ru_text($Name),$Lv,helper::get_race($Race),round($PvpPoint),$id);
						$i++;
			}	
			$result = $table->generate();
			helper::setCache('top100',$result);
		}
		return $result;
	}
//гильдии
	function guild() {
		if(!$result=helper::getCache('guild')){
			$world=WORLD;
			$query=db_mssql_query("SELECT id,CreateDt,Grade,MemberCount,Race FROM $world.dbo.tbl_Guild");
			$table=new CI_Table;
			$tmpl = array (
				'table_open'=>'<table cellspacing="0"><thead>',
				'heading_cell_start'=>'<th>',
				'heading_cell_end'=>'</th>',
				'row_start'=>'</thead><tr class="tc">',
				'row_alt_start'=>'<tr class="tc">',
						);
			$table->set_template($tmpl);
			$table->set_heading('№', 'Имя гильдии','Дата создания','Раса','Грейд','Игроков');
			$i=1;
			while (list($id,$CreateDt,$Grade,$MemberCount,$Race) = db_mssql_fetchrow($query))
			{
				$table->add_row ($i,helper::ru_text($id),$CreateDt,helper::get_race($Race,false),$Grade,$MemberCount);
				$i++;
			}	
			$result = $table->generate();
			
			helper::setCache('guild',$result);
		}
		return $result;
	}
//названия ламп
	function show_lider_rank($num) {
		if($num==0) return 'Патриарх';
		if($num==1) return 'Архонт';
		if($num==2) return 'Атакующий';
		if($num==3) return 'Защитник';
		if($num==4) return 'Поддержка';
		if($num==5) return 'Назначен Архонтом';
		if($num==6) return 'Назначен Атакующим';
		if($num==7) return 'Назначен Защитником';
		if($num==8) return 'Назначен в Поддержку';
		return 'Не назначен';
	}
//лидеры рас
    function liders() {
			$table=new CI_Table;
			$tmpl = array (
						'table_open'=>'<table cellspacing="0"><thead>',
						'heading_cell_start'=>'<th>',
						'heading_cell_end'=>'</th>',
						'row_start'=>'</thead><tr class="tc">',
						'row_alt_start'=>'<tr class="tc">',
			              );
			$table->set_template($tmpl);
			$db=WORLD;
			
			$query = mssql_query("
	SELECT * FROM {$db}.dbo.tbl_patriarch_candidate
	WHERE eSerial=(SELECT TOP(1)eSerial FROM {$db}.dbo.tbl_patriarch_candidate ORDER BY eSerial DESC)-1
	AND ClassType<>255
	ORDER BY Race,ClassType");
	
			
	        $table->set_heading
	        (
	        	'Имя',
	        	'Уровень',
	        	'Положение в расе',
	        	'Раса',
	        	'Гильдия',
	        	'PvP Очки',
	        	'Количество голосов'
	        );
	                
	        if (mssql_num_rows($query) > 0)
	        {
	           while ($row = mssql_fetch_array($query))
	           {
	
	                	$table->add_row
	                	(
	                		$row['AName'],
	                		$row['Lv'],
	                		helper::show_lider_rank($row['ClassType']),
	                		helper::get_race($row['Race'],false),
	                		$row['GName'],
	                		intval($row['PvpPoint']),
	                		$row['Score']
	                	);
	            	
	           }
	        }
	        
	        $result =  $table->generate();
	        
		
		return $result;
    }
//проверка фг бана
	function check_fg($reason) {
		$summ=md5($reason);
		if ($summ=='5176ab10b14b8a9a60f819ea0ea25090') return 'FireGuard Ban';
		if ($summ=='8192a31fab90dcc5d51bf57e538747fa') return 'FireGuard Ban';
		if ($reason=='') return 'нет причины';
		return $reason;
	}
//проверка бана
	function get_bantype($kind) {
		if($kind=='0') return '<font color="red">Бан аккаунта</font>';
		if($kind=='1') return '<font color="lime">Бан чата</font>';
	}
//проверка срока
	function get_period($p,$k) {
		if($k=='0') return "$p дней";
		if($k=='1') return "$p часов";
	}
/**
 * Список игроков на аккаунте
 *
 * @param string $Account 
 * @return void
 * @author NetSoul
 */
	function char_list($Account) {
		$world=WORLD;
		$list=array();
		$query = db_mssql_query ("
		SELECT 
			Name
		FROM 
			$world.dbo.tbl_base
		WHERE
			Account='$Account'
		AND
			DCK=0
		");
		while (list($Name) = db_mssql_fetchrow($query))
		{
			$list[]=helper::ru_text($Name);
		}	
		if(count($list)){
			return implode(', ',$list);
		} else return '<font color="red">нету персонажей</font>';
		return $list;
	}
//проверка логина
	function get_login($AccountSerial) {
		$world=WORLD;
		$query = db_mssql_query ("
		SELECT 
			Account
		FROM 
			$world.dbo.tbl_base
		WHERE
			AccountSerial=$AccountSerial
		");
		while (list($Account) = db_mssql_fetchrow($query))
		{
			return $Account;
		}	
	}
//бан лист
	function banlist() {
		$query = db_mssql_query ('
		SELECT 
			dtStartDate,nPeriod,nKind,szReason,nAccountSerial
		FROM 
			rf_user.dbo.tbl_UserBan
		ORDER BY 
			dtStartDate 
		DESC');
		
		$table=new CI_Table;
		$tmpl = array (
					'table_open'=>'<table cellspacing="0"><thead>',
					'heading_cell_start'=>'<th>',
					'heading_cell_end'=>'</th>',
					'row_start'=>'</thead><tr class="tc">',
					'row_alt_start'=>'<tr class="tc">',
		);
		
		$table->set_template($tmpl);
		$table->set_heading('Дата','Персонажи','Срок','Тип','Причина');
		while (list($dtStartDate,$nPeriod,$nKind,$szReason,$nAccountSerial) = db_mssql_fetchrow($query))
		{
			$reason	=	helper::check_fg($szReason);
			$type	=	helper::get_bantype($nKind);
			$period	=	helper::get_period($nPeriod,$nKind);
			$table->add_row (date("Y.m.d H:i:s",strtotime($dtStartDate)), helper::char_list(helper::get_login($nAccountSerial)),$period,$type,$reason);
		}
		$result =  $table->generate();	
	
		return $result;
	
	}
	
	function show_account_info() {
		if (!isset($_SESSION['aLogin'])) die ('Попытка взлома!');
		$result=db_mssql_query("SELECT * FROM rf_user.dbo.tbl_UserAccount WHERE id='".$_SESSION['aLogin']."'");
		@extract(db_mssql_fetchrow($result));
		list($Password,$Email) = db_mssql_fetchrow(db_mssql_query("SELECT Password, Email FROM rf_user.dbo.".ACC." WHERE Id = '".$_SESSION['aLogin']."'"));
		//list($Password) = db_mssql_fetchrow(db_mssql_query("SELECT Password FROM rf_user.dbo."._ACC_." WHERE Id = '".$Account."'"));
		list($TrunkPass,$HintAnswer)=db_mssql_fetchrow(db_mssql_query("SELECT TrunkPass, HintAnswer FROM ".WORLD.".dbo.tbl_AccountTrunk WHERE AccountSerial='".$serial."'"));
		$uilock_pw=($uilock_pw=='')?'Не имеет':$uilock_pw;
		$uilock_hintanswer=($uilock_hintanswer=='')?__NOTHAVE:$uilock_hintanswer;
		//$text=echotable('class="tab"');
		$text=$serial;
		$text.=$_SESSION['aLogin'];
		$text.=$Password;
		$text.='<a href="mailto:'.$Email.'">'.$Email.'</a>';
		$text.=$createip;
		$text.=$lastconnectip;
		$text.=$createtime;
		$text.=$lastlogintime;
		$text.=$lastlogofftime;
		$text.=$TrunkPass;
		$text.=$HintAnswer;
		$text.=$uilock_pw;
		$text.=$uilock_hintanswer;
		$text.=helper::Cheack_B_SA($serial);
		return $text.'<br /><div align="center"><a href="javascript:history.go(-1)">Вернуться назад</a></div>';
	}
	
	function Cheack_B_SA($SA) {
		list($dtStartDate,$nPeriod,$nKind,$szReason) = db_mssql_fetchrow(db_mssql_query("SELECT dtStartDate, nPeriod, nKind, szReason FROM rf_user.dbo.tbl_UserBan WHERE nAccountSerial = '$SA'"));
		if( $dtStartDate !='' )
		{
			if($nKind==0) return "<b><a title='$szReason'><font color=red>Бан аккаунта(".$nPeriod.")</font></a></b>";
			if($nKind==1) return "<b><a title='$szReason'><font color=red>бан чата(".$nPeriod.")</font></a></b>";
		}
		return "<font color=lime>Рабочий</font>";
	}
}